<script setup>
import {ref, onMounted, reactive, toRefs} from 'vue'
import axios from 'axios'
import {CaretRight, Delete, Edit, Setting} from "@element-plus/icons-vue";

let roleList = ref([])

let rightList = ref([])
let setRightDialogVisible = ref(false)
let treeProps = ref({
  label: 'authName',
  children: 'children',
})
// 树形控件默认选中的节点id值数组
let defKeys = ref([])
let treeRef = ref([])
let roleId = ref(0)
let addDialogVisible = ref(false)
let editDialogVisible = ref(false)
let addRoleFormRef = ref()
let addRoleForm = ref({
  roleName: '',
  roleDesc: '',
})
let editRoleFormRef = ref()
let editRoleForm = ref({
  roleId:'',
  roleName: '',
  roleDesc: '',
})
let addRoleFormRules = ref({
      roleName: [
        {required: true, message: '请输入角色名称', trigger: 'blur'},
        {min: 3, max: 10, message: '长度在 3 到 15 个字符', trigger: 'blur'}
      ],
      roleDesc: [
        {required: false, message: '请输入角色描述', trigger: 'blur'},
        {min: 3, max: 10, message: '长度在 3 到 20 个字符', trigger: 'blur'}
      ]
    }
)
let editRoleFormRules = ref({
      roleName: [
        {required: true, message: '请输入角色名称', trigger: 'blur'},
        {min: 3, max: 10, message: '长度在 3 到 15 个字符', trigger: 'blur'}
      ],
      roleDesc: [
        {required: false, message: '请输入角色描述', trigger: 'blur'},
        {min: 3, max: 10, message: '长度在 3 到 20 个字符', trigger: 'blur'}
      ]
    }
)
const getRoleList = async () => {
  const {data: res} = await axios.get('roles')
  if (res.meta.status !== 200) {
    ElMessage.error("请求角色列表失败")
    return
  }
  // roleList = res.data
  // Object.assign(roleList, res.data)
  roleList.value = res.data
}

const removeRightById = async (role, rightId) => {
  const confirmResult = await ElMessageBox.confirm(
      '次操作将永久删除改权限，是否继续?',
      '提示',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  ).catch(error => error)
  // 点击取消按钮
  if (confirmResult !== 'confirm') {
    ElMessage.info('取消删除')
    return
  }

  const {data: res} = await axios.delete(`roles/${role.id}/rights/${rightId}`)
  if (res.meta.status !== 200) {
    ElMessage.error('删除权限失败')

  } else {
    ElMessage.success('删除权限成功')
    Object.assign(role.children, res.data)
  }
}
const showSetRightDialog = async (role) => {
  const {data: res} = await axios.get('rights/tree')
  if (res.meta.status !== 200) {
    ElMessage.error('请求权限树失败')
    return
  }
  roleId.value = role.id
  // console.log(res.data)
  rightList.value = res.data
  // Object.assign(rightList, res.data)
  getLeafKeys(role, defKeys)
  // Object.assign(treeProps,{defaultCheckedKeys:keys})
  // Object.assign(defKeys, keys)

  setRightDialogVisible.value = true
}
const showEditRoleDialog = (roleId) => {
  editDialogVisible.value = true
  editRoleForm.value.roleId = roleId
}
const getLeafKeys = (node, arr) => {
  if (!node.children) {
    arr.value.push(node.id)
    return
  }
  node.children.forEach(item => {
    getLeafKeys(item, arr)
  })
}
const setRightDialogClosed = () => {
  // Object.assign(defKeys, [])
  defKeys.value = []
  // console.log(defKeys)
}

const allotRights = async () => {
  const keys = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys()
  ]
  const idStr = keys.join(',')
  const {data: res} = await axios.post(`roles/${roleId.value}/rights`, {rids: idStr})
  if (res.meta.status !== 200) {
    ElMessage.error('分配权限失败')
    return
  }
  ElMessage.success('分配权限成功')
  getRoleList()
  setRightDialogVisible.value = false
}
// const showShowDialog()=>{
//
// }
const addRole = async () => {
  addDialogVisible.value = true
  // 校验表单
  addRoleFormRef.value.validate(async (valid) => {
    if (!valid) return
    // 发起axios请求,返回promised对象
    const {data: res} = await axios.post(`roles`,
        addRoleForm.value)
    if (res.meta.status !== 201)
      ElMessage.error('更新角色信息失败')
    else {
      await getRoleList()
      ElMessage.success('添加角色成功')
    }
    addDialogVisible.value = false
  })
}

const removeById = async (id) => {
  // 如果用户确认删除，则返回值为字符串 confirm
  // 如果用户取消了删除，则返回值为字符串 cancel
  const confirmResult = await ElMessageBox.confirm(
      '次操作将永久删除改角色，是否继续?',
      '提示',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  ).catch(error => error)
  // console.log(confirmResult)
  // 点击取消按钮
  if (confirmResult !== 'confirm') {
    ElMessage.info('取消删除')
    return
  }
  const {data: res} = await axios.delete(`roles/${id}`)
  if (res.meta.status !== 200) {
    ElMessage.error('删除角色失败')
  } else {
    ElMessage.success('删除角色成功')
    await getRoleList()
  }
}
const editRole = async () => {
  // 校验表单
  editRoleFormRef.value.validate(async (valid) => {
    if (!valid) return
    // 发起axios请求,返回promised对象
    const {data: res} = await axios.put(`roles/${editRoleForm.value.roleId}`,
        {roleName: editRoleForm.value.roleName, roleDesc: editRoleForm.value.roleDesc})
    if (res.meta.status !== 200)
      ElMessage.error('更新角色信息失败')
    else {
      await getRoleList()
      ElMessage.success('修改角色成功')
    }
    editDialogVisible.value = false
  })
}
const addDialogClosed = () => {
  addRoleFormRef.value.resetFields()
  addDialogVisible.value = false
}
const editDialogClosed = () => {
  editRoleFormRef.value.resetFields()
  addDialogVisible.value = false
}
//
onMounted(() => {
  getRoleList()

})


</script>

<template>
  <div>
    <!-- 面包蟹导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="addDialogVisible=true">新增角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <!-- 序号列 -->
      <!--      <el-table-column type="index" ></el-table-column>-->
      <el-table :data="roleList" border stripe>
        <el-table-column type="index"></el-table-column>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template #default="scope">
            <el-row :class="['bdbottom',i1===0 ?'bdtop':'','vcenter']" v-for=" (item1,i1) in scope.row.children"
                    :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag style="margin-left: 50px" closable @close.prevent="removeRightById(scope.row,item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <el-icon>
                  <CaretRight/>
                </el-icon>
              </el-col>
              <!-- 渲染二级、三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2===0 ? '' : 'bdtop' ,'vcenter']" v-for=" (item2,i2) in item1.children"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close.prevent="removeRightById(scope.row,item2.id)">
                      {{ item2.authName }}
                    </el-tag>
                    <el-icon>
                      <CaretRight/>
                    </el-icon>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" :class="[i3===0 ? '' : 'bdtop' ]" v-for=" (item3,i3) in item2.children"
                            :key="item3.id" closable @close.prevent="removeRightById(scope.row,item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" size="small" @click="showEditRoleDialog(scope.row.id)"></el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="removeById(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" :icon="Setting" size="small"
                         @click="showSetRightDialog(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 弹窗区域对话框 添加角色 -->
    <el-dialog
        title="添加角色"
        width="50%"
        v-model="addDialogVisible"
        @close="addDialogClosed()">
      <!-- 添加角色表单主体内容区域 -->
      <span>
        <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="70px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName" type="text" placeholder="角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc" type="text" placeholder="角色描述"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="addDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="addRole()">
          Confirm
        </el-button>
      </template>
    </el-dialog>


    <!-- 弹窗区域对话框 修改角色 -->
    <el-dialog
        title="修改角色"
        width="50%"
        v-model="editDialogVisible"
        @close="editDialogClosed()">
      <!-- 修改用户表单主体内容区域 -->
      <span>
        <el-form :model="editRoleForm" :rules="editRoleFormRules" ref="editRoleFormRef" label-width="70px">
          <el-form-item label="角色名称" prop="roleName">
             <el-input v-model="editRoleForm.roleName" type="text">></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
             <el-input v-model="editRoleForm.roleDesc" type="text"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="editDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="editRole()">
          Confirm
        </el-button>
      </template>
    </el-dialog>

    <!-- 弹窗区域对话框 分配权限 -->
    <el-dialog
        title="分配权限"
        width="50%"
        v-model="setRightDialogVisible"
        @close="setRightDialogClosed()"
    >
      <!-- 添加用户表单主体内容区域 -->
      <span>
        <!-- 树形控件 -->
         <el-tree :data="rightList"
                  :props="treeProps"
                  show-checkbox
                  node-key="id"
                  default-expand-all
                  :default-checked-keys="defKeys"
                  ref="treeRef">

         </el-tree>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="setRightDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="allotRights()">
          Confirm
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped lang="less">
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
